# coding=utf-8
import sys
import utility
import config
reload(sys)
sys.setdefaultencoding('utf-8')
import xmlrpclib
import MySQLdb
import json
import itertools
from LightMysql import LightMysql
import time
common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(config.url))
common.version()
uid = common.authenticate(config.odooDb, config.username, config.password, {})
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(config.url))
dbconfig = {'host':'123.57.159.46','port': 3306,'user':'manager','passwd':'39865897','db':'ws','charset':'utf8'}
db = LightMysql(dbconfig)


def insertCategory(id_parent_id,odoo_parent_id):
    categorys=db.query("select id,name,parentid from ims_ewei_shop_category where uniacid=4 and parentid="+str(id_parent_id)+" order by parentid ")
    for category in categorys:
        id = models.execute_kw(config.odooDb, uid, config.password, 'product.category', 'create', [{
            "name": category["name"],
            "parent_id":odoo_parent_id,
            "x_external_id1":category["id"]
        }])
        print "inserted : odoo_id:"+str(id)+" "+" external_id:"+str(category["id"])+" "+category["name"]

        db.dml("update ims_ewei_shop_category set odoo_id="+str(id)+" where id="+str(category["id"]))
        child_category=db.query("select count(id) count from ims_ewei_shop_category where uniacid=4 and parentid="+str(category["id"])+" order by parentid ")

        if child_category[0]["count"]>0:
            insertCategory(category["id"],id)

def insertGoods():
    goods=findAllGoods()
    for good in goods:
        price=good["productprice"]
        if price<=0:
            price=good["marketprice"]
        tmplId = models.execute_kw(config.odooDb, uid, config.password, 'product.template', 'create', [{
            'type':"product",
            "name": good["title"],
            #'barcode': good["productsn"],
            'price':float(price),
            'standard_price': float(good["costprice"]),
            'x_external_id1':int(good["id"]),
            'categ_id':int(good["odoo_category_id"]),
            'weight':float(good["costprice"])
        }])

        db.dml("update ims_ewei_shop_goods set odoo_tmpl_id="+str(tmplId)+" where id="+str(good["id"]))
        print  good["title"]+" tmplId:"+str(tmplId)+" pudtId:"

def syncTemplateId():
        goods=findAllGoods()
        for good in goods:
            if good['odoo_id']:
                odooGoods=models.execute_kw(config.odooDb, uid, config.password,
                    'product.product', 'read',
                    [good['odoo_id']], {'fields': ['product_tmpl_id']}
                )
                db.dml("update ims_ewei_shop_goods set odoo_tmpl_id="+str(odooGoods['product_tmpl_id'][0])+" where id="+str(good["id"]))
                print  "tmpl_id sync ok "+good["title"]+" "+str(odooGoods['product_tmpl_id'][0])

def updateGoods():
    goods=findAllGoods()
    for good in goods:
        try:
            price=good["productprice"]
            if price<=0:
                price=good["marketprice"]

            models.execute_kw(config.odooDb, uid, config.password, 'product.template', 'write', [[good["odoo_tmpl_id"]], {
                'barcode': good["productsn"],
                #'price':float(price)

            }])
            print "success:"+str(good["id"]+0)+" "+good["title"]
        except Exception,e:
            #print "barcode error:"+str(good["id"]+0)+" "+good["title"]
            print e

def syncAttr():
    goods=findAllGoods()
    for good in goods:
        if good["odoo_tmpl_id"]:
            goodsAttrs=db.query("select id,goodsid,title from ims_ewei_shop_goods_spec where goodsid="+str(good["id"]))
            if goodsAttrs:

                for attr in goodsAttrs:
                    attrId=models.execute_kw(config.odooDb, uid, config.password, 'product.attribute', 'create', [{
                        'name':attr["title"],
                        'x_external_id1':attr["id"],
                    }])
                    valueIds=[]
                    goodsAttrValues=db.query("select id,title from ims_ewei_shop_goods_spec_item where specid="+str(attr["id"]))
                    for goodsAttrValue in goodsAttrValues:
                        attrValueId=models.execute_kw(config.odooDb, uid, config.password, 'product.attribute.value', 'create', [{
                            'attribute_id':attrId,
                            'name':goodsAttrValue["title"],
                            'x_external_id1':goodsAttrValue["id"],

                        }])
                        valueIds.append(attrValueId)

                    models.execute_kw(config.odooDb, uid, config.password, 'product.template', 'write', [[good["odoo_tmpl_id"]], {
                        'attribute_line_ids':[
                            (0,0,{
                                    'attribute_id':attrId,
                                    'value_ids':[(6,0,valueIds)]
                                }
                            )
                        ],
                    }])



                    print "insert attr success:"+str(good["odoo_tmpl_id"])

def syncProductAttrData():
    goods=findAllGoods()
    for good in goods:

        res = models.execute_kw(config.odooDb, uid, config.password,'product.template',
        'read',[good["odoo_tmpl_id"]],{'fields': ['product_variant_ids']})

        goods_options=db.query("select * from ims_ewei_shop_goods_option  where goodsid="+str(good["id"]))
        valuesStrs=[]
        for goods_option in goods_options:
            values=goods_option['title'].split('+')
            values.sort()
            valuesStr="".join(values)
            goods_option["values_str"]=valuesStr

        print "tempid:"+str(good["odoo_tmpl_id"])+" goodsid:"+str(good["id"])
        productIds=res['product_variant_ids']
        for productId in productIds:
            pres = models.execute_kw(config.odooDb, uid, config.password,'product.product',
            'read',[productId],{'fields': ['attribute_value_ids']})
            value_res= models.execute_kw(config.odooDb, uid, config.password,'product.attribute.value',
            'read',[pres['attribute_value_ids']],{'fields': ['name']})
            values=[]
            for v in value_res:
                values.append(v["name"]);
            values.sort()
            valuesStr="".join(values);
            isOk=False;
            for goods_option in goods_options:
                print goods_option["values_str"]
                if valuesStr==goods_option["values_str"]:
                    db.dml("update ims_ewei_shop_goods set last_sync_odoo_time=now() where id="+str(good["id"]));
                    db.dml("update ims_ewei_shop_goods_option set odoo_product_id="+str(productId)+" where id="+str(goods_option["id"]));
                    #print valuesStr+" prodid:"+str(productId)+" spid:"+str(goods_option["id"])
                    isOk=True;
            if not isOk:
                print "optionid:"+str(goods_option["id"])+" productId:"+str(productId)+" odoo_tmpl_id: "+str(good["odoo_tmpl_id"])+" goodsid:"+str(good["id"])+" not match.----------------------------------------"+valuesStr



def findAllGoods():
    #return db.query("select * from view_goods_base_info  ")
    #return db.query("select * from view_goods_base_info where odoo_tmpl_id >0  order by last_sync_odoo_time limit 0,100")
    sql = "select * from view_goods_base_info where odoo_tmpl_id>0 and id in(select goodsid from ims_ewei_shop_goods_option gp inner join view_goods_base_info gb on gb.id=gp.goodsid where odoo_product_id is null)"
    return db.query(sql)






syncProductAttrData()
#insertCategory(0,2)

#insertGoods()
#syncAttr()

#yncTemplateId()
#updateGoods()


#updateGoods()

# readGoods(4566)
